package com.example.myapplication.ui.home;

import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import androidx.swiperefreshlayout.widget.SwipeRefreshLayout;

import com.example.myapplication.old.ChatActivity;
import com.example.myapplication.R;
import com.example.myapplication.old.adapter.ContactAdapter;
import com.example.myapplication.old.entity.User1;

import java.util.ArrayList;
import java.util.List;

public class HomeFragment extends Fragment {

    private RecyclerView recyclerView;//声明RecyclerView
    private ContactAdapter adapter;//声明适配器
    private Context context;
    private List<User1> list = new ArrayList<>();

    public View onCreateView(@NonNull LayoutInflater inflater,
                             ViewGroup container, Bundle savedInstanceState) {
        return inflater.inflate(R.layout.fragment_home, container, false);
    }

    @Override
    public void onViewCreated(@NonNull View view, @Nullable Bundle savedInstanceState) {
        recyclerView =  view.findViewById(R.id.recycler_view_hotsong);
        SwipeRefreshLayout swipeRefreshLayout = view.findViewById(R.id.refresh_layout);
        swipeRefreshLayout.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
            @Override
            public void onRefresh() {

                initData();
                adapter.setData(list);
                swipeRefreshLayout.setRefreshing(false);
            }
        });

        //1 设置布局管理器
        RecyclerView.LayoutManager manager = new LinearLayoutManager(getContext());
        recyclerView.setLayoutManager(manager);
        //2 设置适配器
        adapter = new ContactAdapter();
        recyclerView.setAdapter(adapter);

        //3  设置数据
        initData();
        adapter.setData(list);
        adapter.setUserOnclickListener(new ContactAdapter.UserOnclickListener() {
            @Override
            public void onUserClick(User1 user1, int position) {
                Intent intent = new Intent(getContext(), ChatActivity.class);
                intent.putExtra("Contact",user1);
                startActivity(intent);
            }
        });

    }
    private void initData(){
        for (int i = 0; i < 5; i++) {
            User1 u1 = new User1();
            u1.setUsername("追风少年"+i);
            if (i%2==0){
                u1.setImg(R.drawable.a1);
            }
            else{
                u1.setImg(R.drawable.a2);
            }
            list.add(u1);
        }
    }
}